package com.itheima.askme.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.askme.entity.User;
import com.itheima.askme.mapper.UserMapper;
import com.itheima.askme.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dafei
 * @since 2022-06-14
 */
@Service
@Transactional
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    /**
     * 用户注册
     * @param username
     * @param password
     */
    @Override
    public void regist(String username, String password) {
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,username);
        User one = getOne(wrapper);

        if (one!=null){
            throw  new RuntimeException("账户信息已存在");
        }
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setAvatar("/images/0.gif");
        user.setStatus(User.STATUS_NORMAL);
        save(user);

    }

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public User login(String username, String password) {
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,username);
        wrapper.eq(User::getPassword,password);
        User one = getOne(wrapper);
        if (one==null){
            throw  new RuntimeException("账户信息已存在");
        }

        return one;
    }


    /**
     * 专家排行
     * @return
     */
    @Override
    public List<User> rank() {
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(User::getStatus,User.STATUS_NORMAL);
        wrapper.orderByDesc(User::getScore);
        wrapper.last("limit 10");
        List<User> list = list(wrapper);
        return list;
    }
}
